package com.example.locationtracking.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;

import com.example.locationtracking.utils.LTUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class LocationUpdateReceiver extends BroadcastReceiver implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
	private LocationClient mLocationClient;
	private static final LocationRequest REQUEST = LocationRequest.create()
		      .setInterval(5*1000)      // 5 minutes
		      .setFastestInterval(3*60*1000) // 3 minutes
		      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	
	private Context context;
	
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		// TODO Call http://192.168.1.68:8733/addlocation       
		//Toast.makeText(arg0, "start update location", Toast.LENGTH_SHORT).show();
		context=arg0;
		 if (mLocationClient == null) {
	            mLocationClient = new LocationClient(
	            		arg0,
	                    this,  // ConnectionCallbacks
	                    this); // OnConnectionFailedListener
	            mLocationClient.connect();
	        }
	}
	
	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		// TODO Auto-generated method stub
	
		
	}
	@Override
	public void onConnected(Bundle arg0) {
		// TODO Auto-generated method stub
		 mLocationClient.requestLocationUpdates(
	                REQUEST,
	                (LocationListener) this); 
	}
	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		mLocationClient.disconnect();
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub
		//Toast.makeText(context, "Latitude: "+ arg0.getLatitude() + " Longitude : " + arg0.getLongitude(), Toast.LENGTH_SHORT).show();
		mLocationClient.removeLocationUpdates(this);
		//sendLocation(arg0);
		LTUtils.updateLocation(context, arg0);
	}
	

}
